package com.wy.interceptor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;

import com.wy.base.AbstractWizard;

/**
 * Spring Interceptor Class新建向导页面逻辑类
 * 
 * @author 飞花梦影
 * @date 2021-07-19 13:37:12
 * @git {@link https://github.com/dreamFlyingFlower }
 */
public class InterceptorWizard extends AbstractWizard {

	@Override
	public void addPages() {
		// page = new InterceptorPage(selection);
		// addPage(page);
		setPage(new InterceptorWizardPage(this.getSelection()));
		addPage(getPage());
	}

	@Override
	public boolean performFinish() {
		return super.performFinish("/templates/Interceptor.template");
	}

	@Override
	public void doFinish(String containerName, String packageName, String fileName, IProgressMonitor monitor,
			String templateUri) throws Exception {
		monitor.beginTask("Creating " + fileName, 2);
		IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
		IResource resource = root.findMember(new Path(containerName));
		if (!resource.exists() || !(resource instanceof IContainer)) {
			throwCoreException("Container \"" + containerName + "\" does not exist.");
		}
		IContainer container = (IContainer) resource;
		IJavaProject project = (IJavaProject) container.getProject().getNature("org.eclipse.jdt.core.javanature");
		IPackageFragment ipackage =
				project.getAllPackageFragmentRoots()[0].createPackageFragment(packageName, false, monitor);
		String contents = loadTemplate(containerName, templateUri);
		ipackage.createCompilationUnit(fileName + ".java", contents, false, monitor);
		String appConfig = loadAppConfig(containerName);
		ipackage.createCompilationUnit("AppConfig.java", appConfig, false, monitor);
		monitor.worked(1);
	}

	private String loadAppConfig(String containerName) throws Exception {
		StringBuffer sb = new StringBuffer();
		try (InputStream input = this.getClass().getResourceAsStream("/templates/appconfig.template");
				BufferedReader reader = new BufferedReader(new InputStreamReader(input));) {
			String line = null;
			while ((line = reader.readLine()) != null) {
				System.out.println(line);
				line = line.replaceAll("#classname", fileName);
				line = line.replaceAll("#package", packageName);
				boolean skip = false;
				line = line.replaceAll("#projectname", containerName);
				if (!skip) {
					sb.append(line);
					sb.append("\n");
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}